package com.frogs.ucenter.openplatform.util;


import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PropertyUtil;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.UrlUtil;
import com.frogs.ucenter.openplatform.entity.PostObject;
import com.frogs.ucenter.v1.util.ApiConstants;

public class QqHttpsConnectUtil extends BaseHttpsConnectUtil{
	private final static Logger log = LoggerFactory.getLogger(QqHttpsConnectUtil.class);
	
	private static String APPID ;//网站app id
	private static String APPSECRET ;//网站 app key
	private static Integer TIME_OUT ;//超时时间
	private static String propertiesFileName = "qqopenplatform";
	private static String REDIRECTURI;//重定向地址

	// 通过页面授权code 获取access_token
	public final static String OAUTH_ACCESS_TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
	public final static String OAUTH_ACCESS_TOKEN_URL_PARAMS = "grant_type=authorization_code&client_id=CLIENTID&client_secret=CLIENTSECRET&code=CODE&redirect_uri=REDIRECTURI";
	
	// 通过页面授权access_token 获取openid
	public final static String OAUTH_OPENID_BY_ACCESS_TOKEN_URL = "https://graph.qq.com/oauth2.0/me";
	public final static String OAUTH_OPENID_BY_ACCESS_TOKEN_URL_PARAMS = "access_token=ACCESSTOKEN";
	
	// 通过页面授权access_token 获取nickName
	public final static String OAUTH_NICKNAME_BY_ACCESS_TOKEN_URL = "https://graph.qq.com/user/get_user_info";
	public final static String OAUTH_NICKNAME_BY_ACCESS_TOKEN_URL_PARAMS = "access_token=ACCESSTOKEN&oauth_consumer_key=OAUTHCONSUMERKEY&openid=OPENID";
	
	// 通过refresh token 获取access_token
	public final static String OAUTH_ACCESS_TOKEN_BY_REFRESHTOKEN_URL_PARAMS = "client_id=CLIENTID&client_secret=CLIENTSECRET&refresh_token=REFRESHTOKEN&grant_type=refresh_token";
	
	static{
		APPID = PropertyUtil.getProperty(propertiesFileName, "appId");
		APPSECRET = PropertyUtil.getProperty(propertiesFileName, "appSecret");
		TIME_OUT = PropertyUtil.getIntProperty(propertiesFileName, "timeout" , 20000);
		REDIRECTURI = PropertyUtil.getProperty(propertiesFileName, "redirectUri");
	}
	
	
	/**
	 * 说明:通过用户授权码获取access token
	 * @param code 用户授权码
	 * @param redirectUri 重定向地址
	 * @return JSONObject
	 */
	public static String getAccessTokenByCode(String code) {
		PostObject po = new PostObject();
		po.setContent(OAUTH_ACCESS_TOKEN_URL_PARAMS.replace("CLIENTID", APPID).replace("CLIENTSECRET", APPSECRET).replace("CODE", code).replace("REDIRECTURI", UrlUtil.encode(REDIRECTURI, "utf-8")));
		po.setContentType(ContentTypeEnum.WWW_FORM.toString());
		po.setHeaders(headMap);
		po.setHttps(true);
		po.setUrl(OAUTH_ACCESS_TOKEN_URL);
		po.setTimeOut(TIME_OUT);
		String strResult = getReturnString(po);
		return strResult;
	}
	
	
	/**
	 * 说明:通过refresh token获取access token
	 * @param refresh token 更新token
	 * @return JSONObject
	 */
	public static String getAccessTokenByRefreshToken(String refreshToken) {
		PostObject po = new PostObject();
		po.setContent(OAUTH_ACCESS_TOKEN_BY_REFRESHTOKEN_URL_PARAMS.replace("CLIENTID", APPID).replace("CLIENTSECRET", APPSECRET).replace("REFRESHTOKEN", refreshToken));
		po.setContentType(ContentTypeEnum.WWW_FORM.toString());
		po.setHeaders(headMap);
		po.setHttps(true);
		po.setUrl(OAUTH_ACCESS_TOKEN_URL);
		po.setTimeOut(TIME_OUT);
		String strResult = getReturnString(po);
		return strResult;
	}
	
	/**
	 * 说明:通过access token获取OPENID
	 * @param accessToken 
	 * @return JSONObject
	 * 返回结果： {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"}
	 */
	public static JSONObject getOpenidByAccessToken(String accessToken) {
		PostObject po = new PostObject();
		po.setContent(OAUTH_OPENID_BY_ACCESS_TOKEN_URL_PARAMS.replace("ACCESSTOKEN", accessToken));
		po.setContentType(ContentTypeEnum.WWW_FORM.toString());
		po.setHeaders(headMap);
		po.setHttps(true);
		po.setUrl(OAUTH_OPENID_BY_ACCESS_TOKEN_URL);
		po.setTimeOut(TIME_OUT);
		JSONObject jsonObject = getQqOpenid(po);
		return jsonObject;
	}
	
	/**
	 * 说明:通过access token和OPENID获取nickname
	 * @param accessToken 
	 * @return JSONObject
	 * 返回结果： {"ret":0,"nickname":"Peter"}
	 */
	public static JSONObject getNickname(String accessToken,String openId) {
		JSONObject json = null;
		Map<String, Object> map = new HashMap<String, Object>();
    	if(StringUtil.isEmpty(accessToken)){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "getNickname access token is null");
    		log.error("获取getNickname有误 accessToken为空");
    		json = new JSONObject(map);
    		return json;
    	}
    	if(StringUtil.isEmpty(openId)){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "getNickname openId is null");
    		log.error("获取getNickname有误 openId为空");
    		json = new JSONObject(map);
    		return json;
    	}
		PostObject po = new PostObject();
		po.setContent(OAUTH_NICKNAME_BY_ACCESS_TOKEN_URL_PARAMS.replace("ACCESSTOKEN", accessToken).replace("OAUTHCONSUMERKEY", APPID).replace("OPENID", openId));
		po.setContentType(ContentTypeEnum.WWW_FORM.toString());
		po.setHeaders(headMap);
		po.setHttps(true);
		po.setUrl(OAUTH_NICKNAME_BY_ACCESS_TOKEN_URL);
		po.setTimeOut(TIME_OUT);
		json = get(po);
		int code = json.getIntValue("ret");
		if(0!=code){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "getNickname fail code = "+code);
    		log.error("获取getNickname有误,错误码为code = "+code);
    		json = new JSONObject(map);
    		return json;
		}
		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_SUCCESS);
		map.put(ApiConstants.NICK_NAME, json.getString("nickname"));
		json = new JSONObject(map);
		return json;
	}
	
    /**
     * 通过code获取openid
     * @param code
     * @param redirectUri 回调url
     * @return {"access_token":"123","expires_in":"456","refresh_token":"789","openid":"12345"}
     */
    public static JSONObject getOpenid(String code) {
    	JSONObject json = null;
    	String access_token = "";
    	String expires_in = "";
    	String refresh_token = "";
    	Map<String, Object> map = new HashMap<String, Object>();
    	String strResult = getAccessTokenByCode(code);
    	if(StringUtil.isEmpty(strResult)){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "get access token error");
    		log.error("获取access token 有误 strResult="+strResult+" code="+code);
    		json = new JSONObject(map);
    		return json;
    	}
		String list[] = strResult.split("&");
		for(int i=0;i<list.length;i++){
			if(list[i].split("=").length>0){
				if(list[i].split("=")[0].equalsIgnoreCase("access_token")){
					access_token = list[i].split("=")[1];
				}else if(list[i].split("=")[0].equalsIgnoreCase("expires_in")){
					expires_in = list[i].split("=")[1];
				}else if(list[i].split("=")[0].equalsIgnoreCase("refresh_token")){
					refresh_token = list[i].split("=")[1];
				}
			}
		}

    	if(StringUtil.isEmpty(access_token)){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "access token is null");
    		log.error("获取access token 有误 strResult="+strResult+" code="+code);
    		json = new JSONObject(map);
    		return json;
    	}
    	map.put(ApiConstants.ACCESS_TOKEN, access_token);
    	map.put(ApiConstants.EXPIRES_IN, expires_in);
    	map.put(ApiConstants.REFRESH_TOKEN, refresh_token);
    	json = getOpenidByAccessToken(access_token);
    	if(StringUtil.isEmpty(json.getString("openid"))){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "openid is null");
    		log.error("获取openid 有误 strResult="+strResult+" code="+code);
    		json = new JSONObject(map);
    		return json;
    	}
    	map.put(ApiConstants.OPEN_ID, json.getString("openid"));
    	map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_SUCCESS);
    	json = new JSONObject(map);
        return json;
    }

}
